<template>
  <div class="live-stream-viewer">
    <div class="viewer-header">
      <h3 class="viewer-title">
        <el-icon><VideoPlay /></el-icon>
        实时视频
      </h3>
      <div class="viewer-controls">
        <el-button-group>
          <el-button
            :type="layout === 1 ? 'primary' : 'default'"
            @click="setLayout(1)"
            size="small"
          >
            1路
          </el-button>
          <el-button
            :type="layout === 4 ? 'primary' : 'default'"
            @click="setLayout(4)"
            size="small"
          >
            4路
          </el-button>
        </el-button-group>
        
        <el-button size="small" @click="clearAll" :disabled="activeCameras.length === 0">
          <el-icon><Delete /></el-icon>
          清空
        </el-button>
        
        <el-button 
          size="small" 
          type="success" 
          @click="enterFullscreen" 
          :disabled="activeCameras.length === 0"
        >
          <el-icon><FullScreen /></el-icon>
          全屏
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="viewer-content" :class="{ 'fullscreen-mode': isFullscreen }" ref="viewerContentRef">
      <!-- 全屏退出按钮 -->
      <div v-if="isFullscreen" class="fullscreen-exit" @click="exitFullscreen">
        <el-icon><Close /></el-icon>
        <span>退出全屏</span>
      </div>
      
      <!-- 全屏模式下的头部控制 -->
      <div v-if="isFullscreen" class="fullscreen-header">
        <h3 class="fullscreen-title">
          <el-icon><VideoPlay /></el-icon>
          实时视频监控 - 全屏模式
        </h3>
        <div class="fullscreen-controls">
          <el-button-group>
            <el-button
              :type="layout === 1 ? 'primary' : 'default'"
              @click="setLayout(1)"
              size="small"
            >
              1路
            </el-button>
            <el-button
              :type="layout === 4 ? 'primary' : 'default'"
              @click="setLayout(4)"
              size="small"
            >
              4路
            </el-button>
            <!-- <el-button
              :type="layout === 9 ? 'primary' : 'default'"
              @click="setLayout(9)"
              size="small"
            >
              9路
            </el-button>
            <el-button
              :type="layout === 16 ? 'primary' : 'default'"
              @click="setLayout(16)"
              size="small"
            >
              16路
            </el-button> -->
          </el-button-group>
          
          <el-button size="small" @click="clearAll" :disabled="activeCameras.length === 0">
            <el-icon><Delete /></el-icon>
            清空
          </el-button>
        </div>
      </div>
      <!-- 视频网格容器 -->
      <div 
        class="video-grid" 
        :class="`layout-${layout}`"
      >
        <div
          v-for="(slot, index) in videoSlots"
          :key="index"
          class="video-slot"
          :class="{ 'active': slot.camera, 'empty': !slot.camera, 'drag-over': dragOverSlot === index }"
          @dragover.prevent="handleDragOver(index)"
          @dragleave="handleDragLeave"
          @drop.prevent="handleSlotDrop($event, index)"
        >
          <!-- 有摄像头的槽位 -->
          <div v-if="slot.camera && slot.camera.id" class="video-player-container">
            <div class="video-content" @mouseenter="showHoverLayer(index)" @mouseleave="hideHoverLayer(index)">
              <VideoPlayer
                :video-url="slot.camera.url || ''"
                :width="'100%'"
                :height="'100%'"
                :autoplay="true"
                :muted="true"
                :show-custom-controls="false"
                :ref="(el) => setVideoPlayerRef(el, index)"
                @stream-stats-update="(stats) => updateStreamStats(index, stats)"
              />
              
              <!-- 自定义悬浮控制层 -->
              <div 
                v-show="hoverStates[index]" 
                class="video-hover-overlay"
                @mouseenter="showHoverLayer(index)"
                @mouseleave="hideHoverLayer(index)"
              >
                <!-- 顶部信息区域 -->
                <div class="hover-header">
                  <div class="camera-title">
                    <span class="camera-name">{{ slot.camera.name }}</span>
                    <span class="camera-id">ID: {{ slot.camera.id }}</span>
                  </div>
                </div>
                
                <!-- 底部控制区域 -->
                <div class="hover-footer">
                  <div class="stream-info">
                    <span class="bitrate">{{ getStreamBitrate(index) }}</span>
                  </div>
                  
                  <div class="hover-controls">
                    <!-- 云台控制箭头按钮 -->
                    <el-button 
                      v-if="slot.camera && slot.camera.ptzEnable"
                      size="small" 
                      circle
                      class="control-btn ptz-btn"
                      @click="controlPTZ(slot.camera)"
                      title="云台控制"
                    >
                      <el-icon><ArrowUp /></el-icon>
                    </el-button>
                    
                    <el-button 
                      v-if="slot.camera"
                      size="small" 
                      circle
                      class="control-btn record-btn"
                      @click="goToPlayback(slot.camera)"
                      title="转到录像页面"
                    >
                      <el-icon><VideoCamera /></el-icon>
                    </el-button>
                    
                    <el-button 
                      v-if="slot.camera"
                      size="small" 
                      circle
                      :class="['control-btn', slot.paused ? 'play-btn' : 'pause-btn']"
                      @click="togglePause(index)"
                      :title="slot.paused ? '点击播放' : '点击暂停'"
                    >
                      <el-icon v-if="slot.paused" class="play-icon">
                        <VideoPlay />
                      </el-icon>
                      <el-icon v-else class="pause-icon">
                        <VideoPause />
                      </el-icon>
                    </el-button>
                    
                    <el-button 
                      v-if="slot.camera"
                      size="small" 
                      circle
                      class="control-btn fullscreen-btn"
                      @click="enterVideoFullscreen(index)"
                      :title="videoFullscreenStates[index] ? '退出全屏' : '全屏'"
                    >
                      <el-icon><FullScreen /></el-icon>
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 空槽位 -->
          <div v-else class="empty-slot">
            <div class="empty-content">
              <el-icon class="empty-icon"><Plus /></el-icon>
              <span class="empty-text">从左侧目录拖拽添加摄像头</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 全屏视频对话框 -->
    <el-dialog
      v-model="fullscreenVisible"
      :title="fullscreenCamera?.name || ''"
      width="90%"
      center
      :show-close="true"
      @close="closeFullscreen"
    >
      <div class="fullscreen-video">
        <VideoPlayer
          v-if="fullscreenCamera"
          :video-url="fullscreenCamera.url || ''"
          :width="'100%'"
          :height="'600px'"
          :autoplay="true"
          :show-custom-controls="true"
        />
      </div>
      
      <template #footer>
        <div class="fullscreen-controls">
          <el-button @click="controlPTZ(fullscreenCamera)" type="primary">
            <el-icon><SetUp /></el-icon>
            云台控制
          </el-button>
          <el-button @click="closeFullscreen">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, getCurrentInstance } from 'vue'
import {
  ElButton,
  ElButtonGroup,
  ElIcon,
  ElDialog
} from 'element-plus'
import { warning, success, info, error as showError } from '@/utils/toast'
import {
  VideoPlay,
  VideoCamera,
  Delete,
  FullScreen,
  SetUp,
  Close,
  Plus,
  VideoPause,
  ArrowUp
} from '@element-plus/icons-vue'
import VideoPlayer from '@/components/VideoPlayer.vue'

// 接口定义
interface Camera {
  id: string
  name: string
  ip: string
  status: 'online' | 'offline'
  url?: string
  type?: 'camera'
  nvrId?: number
  ptzEnable?: boolean  // 是否支持云台控制
}

interface VideoSlot {
  camera: Camera | null
  recording: boolean
  paused?: boolean
}

// Props
interface Props {
  defaultLayout?: number
  cameras?: Camera[]
}

const props = withDefaults(defineProps<Props>(), {
  defaultLayout: 4,
  cameras: () => []
})

// Emits
const emit = defineEmits<{
  'camera-added': [camera: Camera, slotIndex: number]
  'camera-removed': [camera: Camera, slotIndex: number]
  'control-ptz': [camera: Camera]
  'start-record': [cameras: Camera[]]
  'stop-record': [cameras: Camera[]]
  'go-to-playback': [camera: Camera]
  'playback-status-changed': [data: { camera: Camera, slotIndex: number, isPaused: boolean }]
}>()

// 响应式数据
const layout = ref<number>(props.defaultLayout)
const activeCameras = ref<(Camera | null)[]>([])
const fullscreenVisible = ref(false)
const fullscreenCamera = ref<Camera | null>(null)
const currentTime = ref('')
const recordingCameras = ref<Set<string>>(new Set())
const dragOverSlot = ref<number>(-1)
const isFullscreen = ref(false)
const viewerContentRef = ref<HTMLElement>()
const hoverStates = ref<boolean[]>([])
const pausedStates = ref<boolean[]>([])
const videoPlayerRefs = ref<any[]>([])

// 存储每个视频播放器的实时统计信息
const streamStatsMap = ref<Map<number, any>>(new Map())

// 单个视频全屏状态跟踪
const videoFullscreenStates = ref<boolean[]>([])
const currentFullscreenSlot = ref<number>(-1)

// 计算属性
const videoSlots = computed((): VideoSlot[] => {
  const slots: VideoSlot[] = []
  for (let i = 0; i < layout.value; i++) {
    const camera = activeCameras.value[i] || null
    // 确保只有有效的摄像头对象才被传递
    const validCamera = camera && camera.id ? camera : null
    slots.push({
      camera: validCamera,
      recording: validCamera ? recordingCameras.value.has(validCamera.id) : false,
      paused: pausedStates.value[i] || false
    })
  }
  return slots
})

// 方法
const setLayout = (newLayout: number) => {
  if (newLayout < layout.value && activeCameras.value.length > newLayout) {
    // 如果新布局槽位更少，需要确认是否移除多余的摄像头
    const excessCameras = activeCameras.value.slice(newLayout)
    if (excessCameras.length > 0) {
      warning(`切换到${newLayout}路布局将移除${excessCameras.length}个摄像头`)
      // 可以添加确认对话框
      activeCameras.value = activeCameras.value.slice(0, newLayout)
    }
  }
  layout.value = newLayout
  // 初始化状态数组
  initializeStates()
  // 需要通知布局变化，但不需要传递null摄像头
  // emit('layout-changed', newLayout)
}

const addCamera = (camera: Camera, slotIndex?: number) => {
  if (slotIndex !== undefined) {
    // 指定槽位添加
    if (slotIndex < layout.value) {
      // 确保数组长度足够，填充null到指定索引
      while (activeCameras.value.length <= slotIndex) {
        activeCameras.value.push(null)
      }
      
      // 如果指定槽位已有摄像头，先移除
      if (activeCameras.value[slotIndex]) {
        const oldCamera = activeCameras.value[slotIndex]
        emit('camera-removed', oldCamera, slotIndex)
      }
      
      // 直接设置指定位置
      activeCameras.value[slotIndex] = camera
      
      emit('camera-added', camera, slotIndex)
      success(`已添加摄像头：${camera.name} 到槽位 ${slotIndex + 1}`)
      return true
    }
  } else {
    // 添加到末尾
    if (activeCameras.value.length >= layout.value) {
      warning(`当前布局最多支持${layout.value}路视频`)
      return false
    }
    
    activeCameras.value.push(camera)
    const targetIndex = activeCameras.value.length - 1
    
    emit('camera-added', camera, targetIndex)
    success(`已添加摄像头：${camera.name} 到槽位 ${targetIndex + 1}`)
    return true
  }
  
  return false
}

const removeCamera = (slotIndex: number) => {
  const camera = activeCameras.value[slotIndex]
  if (camera) {
    // 直接设置为null，而不是splice，避免改变其他位置的索引
    activeCameras.value[slotIndex] = null
    recordingCameras.value.delete(camera.id)
    // 清理统计信息
    clearStreamStats(slotIndex)
    emit('camera-removed', camera, slotIndex)
    info(`已移除摄像头：${camera.name}`)
  }
}

const clearAll = () => {
  const removedCameras = activeCameras.value.filter((c): c is Camera => c !== null)
  activeCameras.value = []
  recordingCameras.value.clear()
  // 清理所有统计信息
  streamStatsMap.value.clear()
  
  removedCameras.forEach((camera, index) => {
    emit('camera-removed', camera, index)
  })
  
  info('已清空所有视频')
}


// 视频全屏相关方法
const enterVideoFullscreen = async (slotIndex: number) => {
  console.log('enterVideoFullscreen', slotIndex)
  const camera = activeCameras.value[slotIndex]
  if (!camera) return
  
  // 检查当前是否已经全屏
  const isCurrentlyFullscreen = !!(document.fullscreenElement || 
    (document as any).webkitFullscreenElement || 
    (document as any).msFullscreenElement)
  
  // 如果当前已经是全屏状态，则退出全屏
  if (isCurrentlyFullscreen) {
    await exitVideoFullscreen()
    return
  }
  
  try {
    // 查找对应的视频播放器组件
    const videoPlayerRef = getCurrentInstance()?.refs[`videoPlayer${slotIndex}`] as any
    if (videoPlayerRef && videoPlayerRef.$el) {
      const videoElement = videoPlayerRef.$el.querySelector('video')
      if (videoElement) {
        if (videoElement.requestFullscreen) {
          await videoElement.requestFullscreen()
        } else if (videoElement.webkitRequestFullscreen) {
          await videoElement.webkitRequestFullscreen()
        } else if (videoElement.msRequestFullscreen) {
          await videoElement.msRequestFullscreen()
        }
        
        // 更新全屏状态
        videoFullscreenStates.value[slotIndex] = true
        currentFullscreenSlot.value = slotIndex
        success(`${camera.name} 已进入全屏模式`)
        return
      }
    }
    
    // 备用方案：使用容器全屏
    const videoContainer = document.querySelector(`.video-slot:nth-child(${slotIndex + 1}) .video-content`)
    if (videoContainer) {
      if ((videoContainer as any).requestFullscreen) {
        await (videoContainer as any).requestFullscreen()
      } else if ((videoContainer as any).webkitRequestFullscreen) {
        await (videoContainer as any).webkitRequestFullscreen()
      } else if ((videoContainer as any).msRequestFullscreen) {
        await (videoContainer as any).msRequestFullscreen()
      }
      
      // 更新全屏状态
      videoFullscreenStates.value[slotIndex] = true
      currentFullscreenSlot.value = slotIndex
      success(`${camera.name} 已进入全屏模式`)
    }
  } catch (error) {
    console.error('进入全屏失败:', error)
    warning('进入全屏失败，浏览器可能不支持')
  }
}

// 退出单个视频全屏
const exitVideoFullscreen = async () => {
  try {
    if (document.exitFullscreen) {
      await document.exitFullscreen()
    } else if ((document as any).webkitExitFullscreen) {
      await (document as any).webkitExitFullscreen()
    } else if ((document as any).msExitFullscreen) {
      await (document as any).msExitFullscreen()
    }
    
    // 重置全屏状态
    if (currentFullscreenSlot.value >= 0) {
      videoFullscreenStates.value[currentFullscreenSlot.value] = false
      const camera = activeCameras.value[currentFullscreenSlot.value]
      if (camera) {
        info(`${camera.name} 已退出全屏模式`)
      }
      currentFullscreenSlot.value = -1
    }
  } catch (error) {
    console.error('退出全屏失败:', error)
    warning('退出全屏失败')
  }
}


const closeFullscreen = () => {
  fullscreenVisible.value = false
  fullscreenCamera.value = null
}

const controlPTZ = (camera: Camera | null) => {
  if (camera) {
    emit('control-ptz', camera)
  }
}

// 悬浮层控制方法
const showHoverLayer = (index: number) => {
  hoverStates.value[index] = true
}

const hideHoverLayer = (index: number) => {
  hoverStates.value[index] = false
}

const togglePause = async (index: number) => {
  const camera = activeCameras.value[index]
  if (!camera) return
  
  // 获取对应的VideoPlayer组件引用
  const videoPlayerRef = getVideoPlayerRef(index)
  if (!videoPlayerRef) {
    warning('视频播放器未找到')
    return
  }
  
  try {
    // 调用VideoPlayer的切换播放状态方法
    const success = await videoPlayerRef.togglePlayPause()
    if (success) {
      // 更新本地状态
      pausedStates.value[index] = !pausedStates.value[index]
      const status = pausedStates.value[index] ? '已暂停' : '已播放'
      info(`${camera.name} ${status}`)
      
      // 触发播放状态变化事件
      emit('playback-status-changed', {
        camera,
        slotIndex: index,
        isPaused: pausedStates.value[index]
      })
    } else {
      warning('播放状态切换失败')
    }
  } catch (error) {
    console.error('切换播放状态时出错:', error)
    warning('播放状态切换失败')
  }
}

// 设置VideoPlayer组件引用
const setVideoPlayerRef = (el: any, index: number) => {
  if (el) {
    videoPlayerRefs.value[index] = el
  }
}

// 获取VideoPlayer组件引用的辅助方法
const getVideoPlayerRef = (index: number) => {
  return videoPlayerRefs.value[index]
}

const goToPlayback = (camera: Camera | null) => {
  if (camera) {
    // 这里可以导航到录像页面或触发相关事件
    emit('go-to-playback', camera)
    info(`转到 ${camera.name} 的录像页面`)
  }
}

// 获取实时码流信息
const getStreamBitrate = (slotIndex: number): string => {
  const stats = streamStatsMap.value.get(slotIndex)
  if (stats && stats.bitrate > 0) {
    return `${stats.bitrate} Kbps`
  }
  return '-- Kbps'
}

// 更新视频播放器统计信息
const updateStreamStats = (slotIndex: number, stats: any) => {
  streamStatsMap.value.set(slotIndex, stats)
}

// 清理视频播放器统计信息
const clearStreamStats = (slotIndex: number) => {
  streamStatsMap.value.delete(slotIndex)
}

// 初始化状态数组
const initializeStates = () => {
  hoverStates.value = new Array(layout.value).fill(false)
  pausedStates.value = new Array(layout.value).fill(false)
  videoFullscreenStates.value = new Array(layout.value).fill(false)
  videoPlayerRefs.value = new Array(layout.value).fill(null)
}

// 全屏相关方法
const enterFullscreen = async () => {
  if (!viewerContentRef.value) return
  
  try {
    if (viewerContentRef.value.requestFullscreen) {
      await viewerContentRef.value.requestFullscreen()
    } else if ((viewerContentRef.value as any).webkitRequestFullscreen) {
      await (viewerContentRef.value as any).webkitRequestFullscreen()
    } else if ((viewerContentRef.value as any).msRequestFullscreen) {
      await (viewerContentRef.value as any).msRequestFullscreen()
    }
    isFullscreen.value = true
    success('已进入全屏模式')
  } catch (error) {
    console.error('进入全屏失败:', error)
    warning('进入全屏失败，浏览器可能不支持')
  }
}

const exitFullscreen = async () => {
  try {
    if (document.exitFullscreen) {
      await document.exitFullscreen()
    } else if ((document as any).webkitExitFullscreen) {
      await (document as any).webkitExitFullscreen()
    } else if ((document as any).msExitFullscreen) {
      await (document as any).msExitFullscreen()
    }
    isFullscreen.value = false
    info('已退出全屏模式')
  } catch (error) {
    console.error('退出全屏失败:', error)
    warning('退出全屏失败')
  }
}

// 监听全屏状态变化
const handleFullscreenChange = () => {
  const isCurrentlyFullscreen = !!(document.fullscreenElement || 
    (document as any).webkitFullscreenElement || 
    (document as any).msFullscreenElement)
  
  // 处理整个组件的全屏状态
  if (!isCurrentlyFullscreen && isFullscreen.value) {
    isFullscreen.value = false
    info('已退出全屏模式')
  }
  
  // 处理单个视频的全屏状态
  if (!isCurrentlyFullscreen && currentFullscreenSlot.value >= 0) {
    videoFullscreenStates.value[currentFullscreenSlot.value] = false
    const camera = activeCameras.value[currentFullscreenSlot.value]
    if (camera) {
      info(`${camera.name} 已退出全屏模式`)
    }
    currentFullscreenSlot.value = -1
  }
}

const handleDragOver = (slotIndex: number) => {
  dragOverSlot.value = slotIndex
}

const handleDragLeave = () => {
  dragOverSlot.value = -1
}

const handleSlotDrop = (event: DragEvent, slotIndex: number) => {
  event.preventDefault()
  event.stopPropagation() // 阻止事件冒泡
  dragOverSlot.value = -1
  
  console.log('Slot drop event:', slotIndex)
  
  const cameraData = event.dataTransfer?.getData('text/plain')
  if (cameraData) {
    try {
      const camera = JSON.parse(cameraData) as Camera
      console.log('Parsed camera data:', camera)
      console.log('Camera ptzEnable:', camera.ptzEnable)
      // 确保摄像头数据完整
      if (camera && camera.id && camera.name) {
        console.log('Adding camera to slot:', slotIndex, camera.name, 'ptzEnable:', camera.ptzEnable)
        const success = addCamera(camera, slotIndex)
        console.log('Add camera result:', success)
      } else {
        console.error('摄像头数据不完整:', camera)
        showError('摄像头数据不完整')
      }
    } catch (error) {
      console.error('拖拽数据解析失败:', error)
      showError('拖拽数据解析失败')
    }
  } else {
    console.error('No camera data in drop event')
  }
}

// 更新时间
const updateTime = () => {
  currentTime.value = new Date().toLocaleTimeString('zh-CN')
}

// 暴露方法给父组件
defineExpose({
  addCamera,
  removeCamera,
  clearAll,
  setLayout,
})

// 生命周期
let timeInterval: number | null = null

onMounted(() => {
  updateTime()
  timeInterval = window.setInterval(updateTime, 1000)
  
  // 初始化状态数组
  initializeStates()
  
  // 添加全屏事件监听
  document.addEventListener('fullscreenchange', handleFullscreenChange)
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.addEventListener('msfullscreenchange', handleFullscreenChange)
})

onUnmounted(() => {
  if (timeInterval) {
    window.clearInterval(timeInterval)
  }
  
  // 移除全屏事件监听
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
  document.removeEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.removeEventListener('msfullscreenchange', handleFullscreenChange)
})
</script>

<style scoped>
.live-stream-viewer {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.viewer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  background: #fafafa;
}

.viewer-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.viewer-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.viewer-content {
  flex: 1;
  padding: 16px;
  background: #f5f7fa;
  overflow: hidden;
  position: relative;
}

/* 全屏模式样式 */
.viewer-content.fullscreen-mode {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
  background: #000;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.fullscreen-exit {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10001;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  transition: all 0.3s;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.fullscreen-exit:hover {
  background: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.4);
}

.fullscreen-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: rgba(0, 0, 0, 0.9);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
}

.fullscreen-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: white;
}

.fullscreen-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.fullscreen-mode .video-grid {
  flex: 1;
  padding: 20px;
  background: transparent;
}

.video-grid {
  width: 100%;
  height: 100%;
  display: grid;
  gap: 12px;
}

.layout-1 {
  grid-template-columns: 1fr;
  grid-template-rows: 1fr;
}

.layout-4 {
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 1fr);
}

.layout-9 {
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
}

.layout-16 {
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(4, 1fr);
}

.video-slot {
  background: #2c3e50;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  transition: all 0.3s;
  min-height: 200px;
}

.video-slot.active {
  background: #34495e;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.video-slot.empty {
  background: #ecf0f1;
  border: 2px dashed #bdc3c7;
  transition: all 0.3s;
}

.video-slot.drag-over {
  border-color: #67c23a !important;
  background: #f0f9f0 !important;
  transform: scale(1.02);
  transition: all 0.3s;
}

.video-player-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.video-content {
  flex: 1;
  position: relative;
  background: #000;
  min-height: 0;
}

/* 自定义悬浮控制层 */
.video-hover-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    to bottom,
    rgba(0, 0, 0, 0.7) 0%,
    rgba(0, 0, 0, 0) 30%,
    rgba(0, 0, 0, 0) 70%,
    rgba(0, 0, 0, 0.7) 100%
  );
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  z-index: 10;
  transition: opacity 0.3s ease;
}

.hover-header {
  padding: 12px 16px;
  color: white;
}

.camera-title {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.camera-name {
  font-size: 16px;
  font-weight: 600;
  color: #ffffff;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.camera-id {
  font-size: 12px;
  color: #e8e8e8;
  opacity: 0.9;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);
}

.hover-footer {
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: white;
}

.stream-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stream-info .bitrate {
  font-size: 12px;
  color: #e8e8e8;
  background: rgba(0, 0, 0, 0.6);
  padding: 4px 8px;
  border-radius: 4px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);
}

.hover-controls {
  display: flex;
  gap: 8px;
  align-items: center;
}

.hover-controls .el-button {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  backdrop-filter: blur(5px);
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.hover-controls .el-button:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
}

.hover-controls .el-button.el-button--info {
  background: rgba(144, 202, 249, 0.3);
  border-color: rgba(144, 202, 249, 0.5);
}

.hover-controls .el-button.el-button--info:hover {
  background: rgba(144, 202, 249, 0.5);
  border-color: rgba(144, 202, 249, 0.7);
}

.hover-controls .el-button.el-button--warning {
  background: rgba(255, 193, 7, 0.3);
  border-color: rgba(255, 193, 7, 0.5);
}

.hover-controls .el-button.el-button--warning:hover {
  background: rgba(255, 193, 7, 0.5);
  border-color: rgba(255, 193, 7, 0.7);
}

.hover-controls .el-button.el-button--success {
  background: rgba(76, 175, 80, 0.3);
  border-color: rgba(76, 175, 80, 0.5);
}

.hover-controls .el-button.el-button--success:hover {
  background: rgba(76, 175, 80, 0.5);
  border-color: rgba(76, 175, 80, 0.7);
}

.hover-controls .el-button.el-button--primary {
  background: rgba(64, 158, 255, 0.3);
  border-color: rgba(64, 158, 255, 0.5);
}

.hover-controls .el-button.el-button--primary:hover {
  background: rgba(64, 158, 255, 0.5);
  border-color: rgba(64, 158, 255, 0.7);
}

.empty-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.empty-content {
  text-align: center;
  color: #95a5a6;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
  color: #bdc3c7;
}

.empty-text {
  display: block;
  font-size: 16px;
  color: #7f8c8d;
  font-weight: 500;
  margin-bottom: 4px;
}

.empty-hint {
  display: block;
  font-size: 12px;
  color: #95a5a6;
}

.video-slot.drag-over .empty-text {
  color: #67c23a;
}

.video-slot.drag-over .empty-hint {
  color: #85ce61;
}

.fullscreen-video {
  width: 100%;
  min-height: 600px;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

.fullscreen-controls {
  display: flex;
  justify-content: center;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .video-grid {
    gap: 8px;
  }
  
  .viewer-content {
    padding: 12px;
  }
  
  .fullscreen-mode .video-grid {
    padding: 15px;
  }
  
  .hover-header {
    padding: 10px 12px;
  }
  
  .hover-footer {
    padding: 10px 12px;
  }
  
  .camera-name {
    font-size: 14px;
  }
  
  .camera-id {
    font-size: 11px;
  }
}

@media (max-width: 768px) {
  .viewer-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .viewer-controls {
    justify-content: center;
  }
  
  .layout-4, .layout-9, .layout-16 {
    grid-template-columns: 1fr;
    grid-template-rows: repeat(4, 1fr);
  }
  
  .empty-icon {
    font-size: 36px;
  }
  
  .empty-text {
    font-size: 14px;
  }
  
  .fullscreen-header {
    flex-direction: column;
    gap: 12px;
    padding: 15px;
  }
  
  .fullscreen-controls {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .fullscreen-mode .layout-9 {
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(5, 1fr);
  }
  
  .fullscreen-mode .layout-16 {
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(6, 1fr);
  }
  
  /* 移动端悬浮层调整 */
  .hover-header {
    padding: 8px 10px;
  }
  
  .hover-footer {
    padding: 8px 10px;
  }
  
  .camera-name {
    font-size: 13px;
  }
  
  .camera-id {
    font-size: 10px;
  }
  
  .hover-controls {
    gap: 6px;
  }
  
  .hover-controls .el-button {
    padding: 6px;
    min-height: 28px;
    min-width: 28px;
  }
  
  .stream-info .bitrate {
    font-size: 10px;
    padding: 2px 6px;
  }
}

@media (max-width: 480px) {
  .layout-1,
  .layout-4,
  .layout-9,
  .layout-16 {
    grid-template-columns: 1fr;
    grid-template-rows: repeat(2, 1fr);
  }
  
  .viewer-content {
    padding: 8px;
  }
  
  .video-grid {
    gap: 6px;
  }
  
  .video-slot {
    min-height: 150px;
  }
  
  .fullscreen-mode .video-grid {
    padding: 10px;
  }
  
  .fullscreen-exit {
    top: 10px;
    right: 10px;
    padding: 6px 12px;
    font-size: 12px;
  }
  
  .fullscreen-header {
    padding: 10px;
  }
  
  .fullscreen-title {
    font-size: 16px;
  }
  
  .fullscreen-mode .layout-1 {
    grid-template-columns: 1fr;
    grid-template-rows: 1fr;
  }
  
  .fullscreen-mode .layout-4 {
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, 1fr);
  }
  
  .fullscreen-mode .layout-9 {
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(5, 1fr);
  }
  
  .fullscreen-mode .layout-16 {
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(8, 1fr);
  }
  
  /* 小屏幕悬浮层调整 */
  .hover-header {
    padding: 6px 8px;
  }
  
  .hover-footer {
    padding: 6px 8px;
    flex-direction: column;
    gap: 8px;
    align-items: stretch;
  }
  
  .camera-name {
    font-size: 12px;
  }
  
  .camera-id {
    font-size: 9px;
  }
  
  .hover-controls {
    justify-content: center;
    gap: 4px;
  }
  
  .hover-controls .el-button {
    padding: 4px;
    min-height: 24px;
    min-width: 24px;
  }
  
  .stream-info {
    justify-content: center;
  }
  
  .stream-info .bitrate {
    font-size: 9px;
    padding: 2px 4px;
  }
}

/* 统一控制按钮样式 */
.control-btn {
  border: none !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15) !important;
  transition: all 0.3s ease !important;
}

.control-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25) !important;
}

/* PTZ控制按钮 - 绿色渐变 */
.ptz-btn {
  background: linear-gradient(135deg, #67c23a, #85ce61) !important;
  color: white !important;
}

.ptz-btn:hover {
  background: linear-gradient(135deg, #5daf34, #73c956) !important;
}

/* 录像按钮 - 蓝色渐变 */
.record-btn {
  background: linear-gradient(135deg, #409eff, #66b1ff) !important;
  color: white !important;
}

.record-btn:hover {
  background: linear-gradient(135deg, #337ecc, #529bff) !important;
}

/* 播放按钮 - 绿色渐变 */
.play-btn {
  background: linear-gradient(135deg, #67c23a, #85ce61) !important;
  color: white !important;
}

.play-btn:hover {
  background: linear-gradient(135deg, #5daf34, #73c956) !important;
}

/* 暂停按钮 - 红色渐变 */
.pause-btn {
  background: linear-gradient(135deg, #f56c6c, #f78989) !important;
  color: white !important;
}

.pause-btn:hover {
  background: linear-gradient(135deg, #f45656, #f67e7e) !important;
}

/* 播放/暂停图标样式 */
.play-icon {
  font-size: 14px;
}

.pause-icon {
  font-size: 14px;
}

/* 全屏按钮 - 紫色渐变 */
.fullscreen-btn {
  background: linear-gradient(135deg, #909399, #b1b3b8) !important;
  color: white !important;
}

.fullscreen-btn:hover {
  background: linear-gradient(135deg, #7a7d85, #9ca0a6) !important;
}
</style>